package com.example.market_management.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.market_management.mapper.userMapper;
import com.example.market_management.model.User;
import com.example.market_management.model.vo.CommonResult;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("user")
@CrossOrigin
public class userController {

    @Autowired
    private userMapper  userMapper;

    /**
     * 注册接口
     * @param user  用户实体类
     * @return
     */
    @PostMapping("/register")
    public CommonResult  register(User user){
        //先判断是否存在用户名,存在则不让其注册，需更换用户名
        String userName=user.getUserName();
        String phoneNumber=user.getPhoneNumber();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_name",userName);
        queryWrapper.or();
        queryWrapper.eq("phone_number",phoneNumber);
        User user1 =userMapper.selectOne(queryWrapper);
        if(user1 !=null){
            return CommonResult.failed("用户已经存在");
        }
        //登录密码加密
       String userPassword=user.getUserPassword();
       String encodeUserPassword= DigestUtils.md5DigestAsHex(userPassword.getBytes());
       //支付密码加密，默认000000
        String encodePayCode=DigestUtils.md5DigestAsHex("000000".getBytes());
        user.setPayCode(encodePayCode);
       user.setCredit(100);
       user.setHeadImage("https://pic2.zhimg.com/v2-53a998cf40e0e36d3e83804d1f39031a_r.jpg");
       int i=userMapper.insert(user);
       if(i==1){
           return CommonResult.success("添加用户成功");
       }
       else {
           return CommonResult.failed(500,"添加用户失败");
       }
    }


    /**
     * 登录接口
     * @param userName  用户名或者手机号
     * @param userPassword
     * @return
     */
    @GetMapping("/login/{userName}/{userPassword}")
    public  CommonResult  login(@PathVariable  String userName, @PathVariable  String userPassword){
        //通过用户名或者手机号登录
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_name",userName);
        queryWrapper.or();
        queryWrapper.eq("phone_number",userName);
        queryWrapper.eq("user_password",userPassword);
        User user=userMapper.selectOne(queryWrapper);
        if(user!=null){
            return CommonResult.success(user);
        }
        else {
            return  CommonResult.failed("没有该用户信息");
        }
    }


    /**
     * 根据用户Id查询用户信息
     * @param userId
     * @return
     */
    @GetMapping("/userInfo/{userId}")
    public CommonResult  userInfo(@PathVariable Integer userId){
        User user=userMapper.selectById(userId);
        if(user!=null){
            return CommonResult.success("查询用户信息成功",user);
        }
        else {
            return  CommonResult.failed("没有该用户信息");
        }
    }



}
